package com.vst.orm.dao;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class BaseDAODispatcher {
	protected Map<String, Object> specificDAOs;

	public void setSpecificDAOs(Map<String, Object> specificDAOs) {
		this.specificDAOs = specificDAOs;
	}

	protected Object getSpecificDAO(String className) {
		return this.specificDAOs == null ? null : this.specificDAOs.get(className);
	}

	protected Object callMethod(Object specificDAO, String methodName, Object... args) {
		try {
			return DAOUtil.callMethod(specificDAO, methodName, args);
		} catch (IllegalArgumentException e) {
			throw new DAODispatcherException(e);
		} catch (NoSuchMethodException e) {
			throw new DAODispatcherException(e);
		} catch (IllegalAccessException e) {
			throw new DAODispatcherException(e);
		} catch (InvocationTargetException e) {
			throw new DAODispatcherException(e);
		}
	}

	protected Object callMethod(Object specificDAO, String methodName, Class<?>[] paramTypes, Object... args) {
		try {
			return DAOUtil.callMethod(specificDAO, methodName, paramTypes, args);
		} catch (IllegalArgumentException e) {
			throw new DAODispatcherException(e);
		} catch (NoSuchMethodException e) {
			throw new DAODispatcherException(e);
		} catch (IllegalAccessException e) {
			throw new DAODispatcherException(e);
		} catch (InvocationTargetException e) {
			throw new DAODispatcherException(e);
		}
	}

	protected static Class<?> getTypeFromArray(Object[] array) {
		if (array == null) {
			return null;
		}
		if (!array.getClass().getComponentType().equals(Object.class)) {
			return array.getClass().getComponentType();
		}
		Class<?> klass = null;
		for (Object o : array) {
			if ((o != null) && ((klass == null) || (o.getClass().isAssignableFrom(klass)))) {
				klass = o.getClass();
			}
		}
		return klass;
	}

	protected static Class<?> getUniformArrayType(Object[] array) {
		if (array == null) {
			return null;
		}
		Class<?> klass = null;
		for (Object o : array) {
			if (o != null) {
				if (klass == null) {
					klass = o.getClass();
				} else if (!klass.equals(o.getClass())) {
					return Object.class;
				}
			}
		}
		return klass;
	}
}
